package io.github.wppli.domain.message.service;

import io.github.wppli.domain.message.model.entity.PrivateMessageEntity;
import io.github.wppli.domain.message.model.entity.UserMessageEntity;
import io.github.wppli.domain.message.model.repository.IMessageRepository;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author li--jiaqiang 2025−03−04
 */
@Service
public class MessageService {

    private final IMessageRepository messageRepository;

    public MessageService(IMessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    public void saveMessageAsync(PrivateMessageEntity privateMessage) {
        messageRepository.saveMessageAsync(privateMessage);
    }


    public List<UserMessageEntity> queryUnreadMessages(Long receiverId) {

        return messageRepository.queryUnreadMessages(receiverId);
    }


    public String getUserId(SimpMessageHeaderAccessor headerAccessor) {
        // 获取会话属性
        Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
        if (sessionAttributes != null) {
            // 从会话属性中获取 userId
            return (String) sessionAttributes.get("userId");
        }
        return null;
    }

    public void markMessageRead(Long receiverId, Long senderId) {
        messageRepository.markMessageRead(receiverId, senderId);
    }

//    /**
//     * 获取历史消息
//     * @param senderId 发送者id
//     * @param receiverId 接收者id
//     */
//    public List<PrivateMessageEntity> getMessages(Long senderId, Long receiverId) {
//        return messageRepository.findBySenderIdAndReceiverIdOrderByCreatedAtDesc(senderId, receiverId);
//    }
}